package com.ktgj.customer.common;


import com.ktgj.customer.domain.Insurance.dftModel.*;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.annotation.Resource;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DovePayUtils {
    Logger logger = LoggerFactory.getLogger(DovePayUtils.class);
    //测试环境
//    private String dovepayId = "lg@lg.com";
//    private String payPass = "741258";
//    private String office = "BJS531";
//    private String url = "http://test.dovepay.com/BIAServer/services/BIAWebService?wsdl";
//    private String key = "DNIV4XWEXJMPZSKYBABPC54U";
//    private String zczcode = "";
//    private String version = "0.0.1";

    //正式环境

    private String dovepayId = "yuexiaohong@jsj.com.cn";
    private String payPass = "577533";//需要跟业务部门要支付密码
    private String office = "PEK602";
    private String url = "https://www.dovepay.com/BIAServer/services/BIAWebService?wsdl";
    private String key = "SCWN5NWGB7SP3GMRO3589CUF";
    private String zczcode = "";
    private String version = "0.0.1";


    private String getSign(String request) {
//        String md5 = Util.getMd5(request);
        try {
//            String base64 = new Base64().encodeToString(md5.getBytes("UTF-8"));
            PaySign paySign = new PaySign();

            return paySign.sign(request, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 德付通开保
     * */
    public BuyInsuranceOutput buyInsurance(BuyInsuranceInput input) {
        BuyInsuranceOutput output = new BuyInsuranceOutput();
        for (BuyInsuranceInfo buyInsuranceInfo : input.getBuyInsuranceInfos()) {
            SimpleDateFormat sdfBirghday = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat sdfDeparture = new SimpleDateFormat("yyyyMMddHHmm");
            try {
                String ticketNo = buyInsuranceInfo.getTicketNo().replace("-", "");
                buyInsuranceInfo.setTicketNo(ticketNo);
                String replace = buyInsuranceInfo.getProtectBirthday().replace("-", "");
                buyInsuranceInfo.setProtectBirthday(replace);
                String depDateTime = buyInsuranceInfo.getDepDateTime().replace("-", "");
                depDateTime = depDateTime.replace(" ", "");
                depDateTime = depDateTime.replace(":", "");
                buyInsuranceInfo.setDepDateTime(depDateTime);
//                String depDateTime = buyInsuranceInfo.getDepDateTime();
                buyInsuranceInfo.setDepDateTime(depDateTime);
                buyInsuranceInfo.setProtectBirthday(sdfBirghday.format(sdfBirghday.parse(buyInsuranceInfo.getProtectBirthday())));
                buyInsuranceInfo.setDepDateTime(sdfDeparture.format(sdfDeparture.parse(buyInsuranceInfo.getDepDateTime())));
            } catch (ParseException e) {
                e.printStackTrace();
                output.setMessage("日期格式不正确");
                output.setCode("-1");
                return output;
            }
        }

        String baseRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><ipayBuyInsur xmlns=\"http://webservice.bia.acca.com\"><transactionMessage>{0}</transactionMessage></ipayBuyInsur></soap:Body></soap:Envelope>";


        String insuranceInfo = "<INSURINFOS>";

        for (BuyInsuranceInfo info : input.getBuyInsuranceInfos()) {
            insuranceInfo += MessageFormat.format("<INSURINFO>\n" +
                            "\t\t<TICKETNO>{0}</TICKETNO>\n" +
                            "\t\t<INSURNAME>{1}</INSURNAME>\n" +
                            "\t\t<PASSENGERID>{2}</PASSENGERID>\n" +
                            "\t\t<IDTYPE>{3}</IDTYPE>\n" +
                            "\t\t<BIRTHDAY>{4}</BIRTHDAY>\n" +
                            "\t\t<TELPHONE>{5}</TELPHONE>\n" +
                            "\t\t<FLIGHTNO>{6}</FLIGHTNO>\n" +
                            "\t\t<FlIGHTORDER>{7}</FlIGHTORDER>\n" +
                            "\t\t<ORIGINAIR>{8}</ORIGINAIR>\n" +
                            "\t\t<DESTAIR>{9}</DESTAIR>\n" +
                            "\t\t<FLIGHTTIME>{10}</FLIGHTTIME>\n" +
                            "<REMARK>123</REMARK>\n" +
                            "\t\t</INSURINFO>", info.getTicketNo(), info.getProtectName(), info.getProtectCard(), info.getProtectIdType(),
                    info.getProtectBirthday()
                    , info.getProtectPhone(), info.getFlightNo(), info.getFlightIndex(), info.getDepCity(), info.getArrCity(),
                    info.getDepDateTime()).replace("\t", "").replace("\n", "");
            ;
        }
        insuranceInfo += "</INSURINFOS>";


        EnumHelp.InsuranceType insuranceType = EnumHelp.InsuranceType.getEnumByValue(input.getInsuranceType());

        String requestBody = MessageFormat.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\t\t\n" +
                "<CONTENT>" +
                "\t<DOVEPAY_ID>{1}</DOVEPAY_ID>\t\n" +
                "\t<OFFICE>{2}</OFFICE>\t\n" +
                "\t<PAY_PASS>{3}</PAY_PASS>\t\n" +
                "\t<INSUR_CODE>{4}</INSUR_CODE>\t\n" +
                "<ZCZCODE/>\n" +
                "\t{0}<VERSION>{5}</VERSION>\t\n" +
                "</CONTENT>\t", insuranceInfo, dovepayId, office, payPass, insuranceType.toString(), version)
                .replace("\t", "").replace("\n", "");


        String sign = getSign(requestBody);
        String transactionMessage = MessageFormat.format("transactiontype={0}&txnxml={1}&signmsg={2}", "tkDetailBuyInsur", requestBody, sign);
        String request = MessageFormat.format(baseRequest, StringEscapeUtils.escapeHtml(transactionMessage));

        String response = OkHttpUtil.postXmlParams(url, request);

//        String response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body><ipayBuyInsurResponse xmlns=\"http://webservice.bia.acca.com\"><ipayBuyInsurReturn>txnretxml=&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;&lt;CONTENT&gt;&lt;RETCODE&gt;BIABX0001&lt;/RETCODE&gt;&lt;RETMEMO&gt;&#x4FDD;&#x9669;&#x4E1A;&#x52A1;&#x62A5;&#x6587;&#x975E;&#x6CD5;&lt;/RETMEMO&gt;&lt;/CONTENT&gt;&amp;signmsg=</ipayBuyInsurReturn></ipayBuyInsurResponse></soapenv:Body></soapenv:Envelope>";
        response = StringEscapeUtils.unescapeHtml(response);


        // 正则表达式规则
        String regEx = "\\<CONTENT\\>.*\\</CONTENT\\>";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(response);

        if (!matcher.find()) {
            output.setMessage("调用接口返回错误");
            output.setCode("-1");
            return output;
        }
//<CONTENT><RETCODE>BIABX0001</RETCODE><RETMEMO>保险业务报文非法</RETMEMO></CONTENT>
        //<CONTENT><RETCODE>BIABX0002</RETCODE><RETMEMO>保险业务参数错误</RETMEMO></CONTENT>
        String content = matcher.group(0);

        Document doc = null;

        try {
            doc = DocumentHelper.parseText(content);
        } catch (DocumentException e) {
            logger.error("DocumentHelper转换失败", e);
        }


//        <CONTENT>
//	<RETCODE>BIABX9001</RETCODE>
//	<RETMEMO>无有效的交易保单</RETMEMO>
//	<RETURNINFOS>
//		<RETURNINFO>
//			<INSURNAME>薛锋</INSURNAME>
//			<TICKETNO>7814884540935</TICKETNO>
//			<FLIGHTNO>MU2954</FLIGHTNO>
//			<FLAG>fail</FLAG>
//			<DETAILMEMO>您已投保同一日期同一航班的航空意外保险</DETAILMEMO>
//			<REMARK>123</REMARK>
//		</RETURNINFO>
//	</RETURNINFOS>
//</CONTENT>
//        if (!doc.getRootElement().element("RETCODE").getText().equals("BIABX0000")) {
//            output.setMessage(doc.getRootElement().element("RETMEMO").getText());
//            output.setCode("-1");
//            return output;
//        }
//
//<?xml version="1.0" encoding="UTF-8"?>
//<soapenv:
//        Envelope
//        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
//        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
//        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
//	<soapenv:Body>
//		<ipayBuyInsurResponse
//                xmlns="http://webservice.bia.acca.com">
//			<ipayBuyInsurReturn>txnretxml=
//				<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
//				<CONTENT>
//					<RETCODE>BIABX1012</RETCODE>
//					<RETMEMO>代理人金额冻结不足</RETMEMO>
//				</CONTENT>&signmsg=0wGkeI1OgNk3a0weJwz0lXaXQku9DAZ4joL+6xHt5eU=
//			</ipayBuyInsurReturn>
//		</ipayBuyInsurResponse>
//	</soapenv:Body>
//</soapenv:Envelope>


//        <?xml version="1.0" encoding="UTF-8"?><soapenv:
//        Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ipayBuyInsurResponse xmlns="http://webservice.bia.acca.com"><ipayBuyInsurReturn>txnretxml=<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
//       <CONTENT><RETCODE>BIABX9001</RETCODE><RETMEMO>无有效的交易保单</RETMEMO>
//      <RETURNINFOS><RETURNINFO><INSURNAME>崔巍</INSURNAME><TICKETNO>9992174751301</TICKETNO><FLIGHTNO>TV6311</FLIGHTNO><FLAG>fail</FLAG>
//     <DETAILMEMO>-无法获取正确的航班信息</DETAILMEMO><INSURURL></INSURURL><REMARK>123</REMARK></RETURNINFO></RETURNINFOS></CONTENT>&signmsg=tX3qtEtOBD5wKY7dB3zqNRyQDnMf8kZOjoL+6xHt5eU=</ipayBuyInsurReturn></ipayBuyInsurResponse></soapenv:Body></soapenv:Envelope>


        if (!doc.getRootElement().element("RETCODE").getText().equals("BIABX0000")) {
            output.setMessage(doc.getRootElement().element("RETMEMO").getText());
            output.setCode("-1");


        }
        try {
            if (!doc.getRootElement().element("RETCODE").getText().equals("BIABX0000")) {
                if (doc.getRootElement().element("RETURNINFOS").element("RETURNINFO").element("FLAG").getText().equals("fail")) {
                    output.setMessage(doc.getRootElement().element("RETURNINFOS").element("RETURNINFO").element("DETAILMEMO").getText());
                    output.setCode("-1");
                    return output;
                }
            } else if (doc.getRootElement().element("RETCODE").getText().equals("BIABX0000") &&
                    doc.getRootElement().element("RETURNINFOS").element("RETURNINFO").element("FLAG").getText().equals("success")) {
                output.setInsuranceNo(doc.getRootElement().element("RETURNINFOS").element("RETURNINFO").element("DETAILMEMO").getText());
                output.setCode("200");
                return output;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        output.setMessage(content);
        output.setCode("200");
        return output;
    }


}
